var calendar;

$(function () {
    $MB.initTpvMeetingElement();

    //$('#my-tab li:first-child a').tab('show');
    //add by aaron.wei 2019.01.22
    $('.j-tpv-tab li').click(function() {
        var old = $('.j-tpv-tab li.active').data('tab');
        var current = $(this).data('tab');
        if (current != old) {
            $(this).addClass('active').siblings('li').removeClass('active');
            $('div[data-tab="'+ old +'"]').hide();
            $('div[data-tab="'+ current +'"]').show();
            $('#'+old).hide();
            $('#'+current).show();
        }
    });

    $(".tpv-nav-item:first").addClass("active");

    var options = {
        events_source: 'meeting/event/' + $(".tpv-nav-item:first").val() + "?mine=true",
        view: 'month',
        tmpl_path: 'tmpls/',
        tmpl_cache: false,
        modal: "#event-detail",
        modal_type: "ajax",
        onAfterEventsLoad: function(events) {
            if(!events) {
                return;
            }
        },
        onAfterViewLoad: function(view) {
            var today1 = new Date().toLocaleDateString();
            var reg = new RegExp("/","g");
            var today = today1.replace(reg,"-");
            $('.btn-group button').removeClass('active');
            $('button[data-calendar-view="' + view + '"]').addClass('active');
            $('h3.page-header').text(this.getTitle());

            $(".events-list a[data-toggle='tooltip']").each(function() {
                var width = $(this).closest(".cal-month-day").width() - 10;
                $(this).css({width: width + 'px'});
            });
        },
        onAfterModalShown: function(events){
//                 initClipboard();
        },
        onAfterModalHidden: function(events){
//              destroyClipboard();
        },
        classes: {
            months: {
                general: 'label'
            }
        }
    };

    calendar = $('#calendar').calendar(options);

    if(LANGUAGE_CODE == 'zh_CN') {
        calendar.setLanguage('zh-CN');
        calendar.view();
    }

    $(".tpv-nav-item").click(function() {
        if(!$(this).hasClass("active")) {
            $(".tpv-nav-item.active").removeClass("active");
            $(this).addClass("active");
            calendar.setOptions({
                events_source: 'meeting/event/' + $(this).val() + "?mine=true",
            });
            calendar.view();
        }
    });

    $('.btn-group button[data-calendar-view]').each(function() {
        var $this = $(this);
        $this.click(function() {
            calendar.view($this.data('calendar-view'));
        });
    });

    $('.btn-group button[data-calendar-nav]').each(function() {
        var $this = $(this);
        $this.click(function() {
            calendar.navigate($this.data('calendar-nav'));
        });
    });

    $("#event-detail .btn-close").click(function() {
        $MB.closeModal("event-detail");
    });

    var $meetingTableForm = $(".meeting-table-form");
    window.operateEvents = {
            'click .recording-manage': function(e, value, row, index) {
                $.get(ctx + "recording/", {"meetingId":row.id}, function (r) {
                    if(r.code === 500){
                        $MB.n_danger(r.msg);
                        return;
                    }
                    if (r.indexOf('tpv-login-layout') !== -1) {
                        top.location.href = location;
                        return;
                    }
                    clearInterval(rediskeysSizeInterval);
                    clearInterval(redisMemoryInfoInterval);
                    $main_content.html("").append(r);
                });
            },
             'click .meeting-detail': function(e, value, row, index) {
                showMeetingDetail(row.id);
             }
        };

    var settings = {
        url: ctx + "meeting/list",
        pageSize: 10,
        clickToSelect: false,
        queryParams: function (params) {
            var startDate =$("input[name='meeting-filter-start-date-link']").val();
            var endDate = $("input[name='meeting-filter-end-date-link']").val();

            var hasDateSelected = (startDate != '') && (endDate != '');


            return {
                pageSize: params.limit,
                pageNum: params.offset / params.limit + 1,
                meetingRoomId:$meetingTableForm.find("select[name='meeting-filter-room-id']").val(),
                userId: $meetingTableForm.find("select[name='meeting-filter-user-id']").val(),
                startDate: (hasDateSelected ? new Date(startDate + " 00:00:00") : undefined),
                endDate: (hasDateSelected ? new Date(endDate + " 23:59:59") : undefined), 
                topic: $("input[name='meeting-filter-topic']").val(),
                // add by Ting.Wong 2018-12-26 15:45 start
                meetingId: $("input[name='meeting-filter-meetingId']").val(),
                // add by Ting.Wong 2018-12-26 15:45 end
                state: $("#filter_state input[name='state']:checked").val(),
            };
        },
        columns: [{
            checkbox: true
        }, {
            field: 'id',
            visible: false
        }, {
            field: 'topic',
            title: $MB.i18n('meeting.list.topic'),
            events: operateEvents,
            width: '160px',
            formatter: function(value, row, index) {
                var info = Handlebars.compile($("#meeting-detail-template").html());
                var retHtml= info({
                                    name: value,
                    });
                return [retHtml].join("");
            }
        }, {
            field: 'content',
            title: $MB.i18n('meeting.list.content'),
            width: '240px',
            formatter: function(value, row, index) {
                var info = Handlebars.compile($("#meeting-content-template").html());
                var retHtml= info({
                                    content: value,
                    });
                return [retHtml].join("");
            }
        }, {
            field: 'meetingRoomName',
            title: $MB.i18n('meeting.list.room'),
            /* chaohung , 20190108 */
            cellStyle: {
                css: {
                    'text-align':'center',
                }
            }
        }, {
            field: 'meetingId',
            title: $MB.i18n('meeting.list.id'),
            /* chaohung , 20190108 */
            cellStyle: {
                css: {
                    'text-align':'center',
                }
            }
        }, {
            field: 'type',
            title: $MB.i18n('meeting.list.repeat'),
            /* chaohung , 20190108 */
            cellStyle: {
                css: {
                    'text-align':'center',
                }
            },
            formatter: function(value, row, index) {
                if(value == '3') {
                    return $MB.i18n('meeting.add.fix');
                } else if(value == '2') {
                    return $MB.i18n('meeting.add.repeat');
                } else if(value == "1") {
                    return $MB.i18n('meeting.add.once');
                } else {
                    return $MB.i18n('meeting.add.now');
                }
            }
        }, {
            field: 'meetingTime',
            title: $MB.i18n('meeting.list.time'),
            /* chaohung , 20190108 */
            cellStyle: {
                css: {
                    'text-align':'center',
                }
            },
            formatter: function(value, row, index) {
                return $MB.formatDate(row.start, row.end);
            }
        }, {
            field: 'durationMessage',
            title: $MB.i18n('meeting.list.duration'),
            formatter: function(value, row, index) {
                if(row.type == '3') {
                    return '';
                }

                return $MB.i18n('meeting.duration.' + value);
            },
            /* chaohung , 20190108 */
            cellStyle: {
                css: {
                    'text-align':'center',
                }
            }
        }, {
            visible: false, // add aaron.wei 2019.01.22
            field: 'username',
            title: $MB.i18n('meeting.list.reservations'),
            /* chaohung , 20190108 */
            cellStyle: {
                css: {
                    'text-align':'center',
                }
            }
        }, {
            field: 'state',
            title: $MB.i18n('meeting.list.state'),
            formatter: function(value, row, index) {
                return $MB.i18n(value);
            },
            cellStyle: {
                css: {
                    'text-align':'center',
                }
            }
        },
           {
             title: $MB.i18n('meeting.list.record'),
             events: operateEvents,
             formatter: function(value, row, index) {
               var retHtml='<button type="button" class="recording-manage btn btn-primary  btn-save" >录像管理</button>';
               return [retHtml].join("");
             },
             /* chaohung , 20190108 */
             cellStyle: {
                 css: {
                     'text-align':'center',
                 }
             }
           }
        ]
    };

    $MB.initTable('meetingTable', settings);

    $(".meeting-table-form input[type=text]").on("keyup",function(){
         if (meeting_search_time) {
            clearTimeout(meeting_search_time);
         }
         meeting_search_time = setTimeout(function() {
            search();
         },300);
    });

    $(".meeting-table-form select").on("change", search);
    $(".dataTables_wrapper input[type=radio]").on("change",  search);
    $("#meeting-filter-start-date").on("change", search);
    $("#meeting-filter-end-date").on("change", search);

    $("#my-schedule-booking").click(function() {
    	var meetingRoomId = $('.tpv-nav-item.active').val();
        var meetingRoomName = $('.tpv-nav-item.active').text();

        addMeeting(meetingRoomId, meetingRoomName, new Date().format("yyyy-mm-dd"), "09:00");
    });
});

function addMeeting(meetingRoomId, meetingRoomName, date, time) {
    var $form = $('#meeting-add');
    $form.modal();
    $form.find("#meeting-add-form").attr("action", "add");

    if(meetingRoomId != null && meetingRoomId.length > 0) {
        $form.find("#select-room").hide();
        $form.find("#is-room").css('display','inline');

        $form.find("input[name='meetingroomName']").val(meetingRoomName);
        $form.find("input[name='meetingroomId']").val(meetingRoomId);
    } else {
        $form.find("#select-room").show();
        $form.find("#is-room").css('display','none');
    }

    if(date != null && date.length > 0) {
        $form.find('#meeting-date').val(date);
        $form.find('#meeting-date-link').val(date);
    }

    if(time != null && time.length > 0) {
        $form.find('#meeting-time').val(time);
        $form.find('#meeting-time-link').val(time);
    }
}


function editMeeting() {
    var selected = $("#meetingTable").bootstrapTable('getSelections');
    var selected_length = selected.length;

    if(!selected_length) {
        $MB.n_warning($MB.i18n('meeting.tips.edit.select.none'));
        return;
    }
    if(selected_length > 1) {
        $MB.n_warning($MB.i18n('meeting.tips.edit.select.many'));
        return;
    }

    doEditMeeting(selected[0].id);
}

function editRepeatMeeting() {
    var selected = $("#meetingTable").bootstrapTable('getSelections');
    var selected_length = selected.length;
    if(!selected_length) {
        $MB.n_warning($MB.i18n('meeting.tips.edit.select.none'));
        return;
    }
    if(selected_length > 1) {
        $MB.n_warning($MB.i18n('meeting.tips.edit.select.many'));
        return;
    }

    if(selected[0].repeatParentId == 0) {
            $MB.n_warning($MB.i18n('meeting.tips.edit.once'));
            return;
    }

    doEditMeeting(selected[0].repeatParentId);
}

function deleteMeeting() {
    var selected = $("#meetingTable").bootstrapTable('getSelections');
    var selected_length = selected.length;

    if (!selected_length) {
        $MB.n_warning($MB.i18n('meeting.tips.delete.select.none'));
        return;
    }
    if (selected_length == 1 && selected[0].repeatParentId != '0') {
        $("#deleteOnce").iCheck("check");
        $("input[name='meetingDeleteId']").val(selected[0].id);
        $('#meeting-delete').modal();
    } else {//多选时只能删除固定会议中的单次会议
        var ids = new Array();
        for(var i=0; i<selected_length; i++) {
            ids.push(selected[i].id);
        }

        $MB.confirm({
            text: $MB.i18n('tips.del.confirm.meeting'),
            confirmButtonText: $MB.i18n('meetingroom.confirm')
        }, function() {
            doDeleteMeeting(ids.join());
        });
    }
}

function doDeleteMeeting(ids, option) {
    $.post(ctx + 'meeting/delete', { "ids": ids, "option": option }, function(r) {
        if (r.code === 0) {
            $MB.n_success(r.msg);
            $MB.refreshTable('meetingTable');
            $MB.closeAndRestModal("meeting-delete");
        } else {
            $MB.n_danger(r.msg);
        }
    });
}

function copyMeetingTxt(e){
      $MB.closeModal(e.attr('id'));
      var meetingId=e.attr('meeting-id');
      openInviteTxt(meetingId);
}

function refresh() {
    $(".meeting-table-form input[type=hidden]").val('');
    $("#filter_state").find(".active").removeClass("active");
    $("#filter_state").find("#toBeJoin").addClass("active");
    $("#filter_state").find("input[type='radio']").removeAttr("checked");
    $("#filter_state").find("#toBeJoin").find("input[type='radio']").attr("checked", true);
    $(".meeting-table-form")[0].reset();

    $MB.refreshTable('meetingTable');
}

function search() {
    $MB.refreshTable('meetingTable');
}

//add by aaron.wei 2019.01.22
function refreshSchedule() {
    $('.j-group-toggle label').removeClass('active');
    //做相应的请求...
}